document.addEventListener('DOMContentLoaded', function() {
    const aiChatBtn = document.getElementById('ai-chat-btn');
    
    // 硅基流动API Key配置
    const API_KEY = "sk-njbpruqunkgshpbqpbyolqnqobdefbrorpbilscksfhtpwua"; // 请替换为实际API Key
    
    // 全局变量，用于控制流式生成
    let isGenerating = false;
    let abortController = null;
    
    aiChatBtn.addEventListener('click', function() {
        openAIChatModal();
    });
    
    function openAIChatModal() {
        // 创建聊天窗口
        const modalHtml = `
            <div class="modal fade" id="ai-chat-modal" tabindex="-1" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title">
                                <i class="bi bi-robot me-2"></i>眼科AI智能问答
                            </h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="chat-container mb-3" style="height: 400px; overflow-y: auto; border: 1px solid #eee; border-radius: 8px; padding: 10px;">
                                <div class="system-message text-center text-muted p-3">
                                    <i class="bi bi-info-circle me-2"></i>
                                    您可以询问关于眼科疾病的任何问题
                                </div>
                            </div>
                            
                            <div class="input-group">
                                <input type="text" class="form-control" id="chat-input" placeholder="输入您的问题...">
                                <button class="btn btn-primary" id="send-message">
                                    <i class="bi bi-send"></i>
                                </button>
                                <button class="btn btn-danger d-none" id="stop-generation">
                                    <i class="bi bi-stop-fill"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 添加模态框到DOM
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 获取模态框实例
        const chatModal = new bootstrap.Modal(document.getElementById('ai-chat-modal'));
        
        // 显示模态框
        chatModal.show();
        
        // 绑定发送消息事件
        document.getElementById('send-message').addEventListener('click', function() {
            sendChatMessage();
        });
        
        // 绑定停止生成按钮事件
        document.getElementById('stop-generation').addEventListener('click', function() {
            stopGeneration();
        });
        
        // 绑定回车键发送消息
        document.getElementById('chat-input').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendChatMessage();
            }
        });
        
        // 模态框关闭时移除DOM
        document.getElementById('ai-chat-modal').addEventListener('hidden.bs.modal', function() {
            // 如果正在生成，停止生成
            if (isGenerating) {
                stopGeneration();
            }
            this.remove();
        });
        
        // 发送聊天消息
        function sendChatMessage() {
            const input = document.getElementById('chat-input');
            const message = input.value.trim();
            
            if (!message) return;
            
            // 检查API Key是否存在
            if (!API_KEY) {
                showAlert('错误', 'API Key未配置，请联系管理员', 'danger');
                return;
            }
            
            // 清空输入框
            input.value = '';
            
            // 添加用户消息
            addChatMessage(message, 'user');
            
            // 创建AI消息容器
            const aiMessageDiv = document.createElement('div');
            aiMessageDiv.className = 'chat-message ai-message p-3 my-2 me-auto';
            aiMessageDiv.style.maxWidth = '80%';
            aiMessageDiv.style.borderRadius = '10px';
            aiMessageDiv.style.backgroundColor = '#f0f5fa';
            aiMessageDiv.innerHTML = '<i class="bi bi-robot me-2"></i><span class="ai-response"></span>';
            
            // 添加到聊天容器
            const chatContainer = document.querySelector('.chat-container');
            chatContainer.appendChild(aiMessageDiv);
            
            // 滚动到底部
            chatContainer.scrollTop = chatContainer.scrollHeight;
            
            // 禁用发送按钮，显示停止按钮
            document.getElementById('send-message').disabled = true;
            document.getElementById('chat-input').disabled = true;
            document.getElementById('send-message').classList.add('d-none');
            document.getElementById('stop-generation').classList.remove('d-none');
            
            // 设置生成状态
            isGenerating = true;
            
            // 创建AbortController用于取消请求
            abortController = new AbortController();
            
            // 设置超时
            const timeoutId = setTimeout(() => {
                if (isGenerating) {
                    stopGeneration();
                    const aiResponseSpan = aiMessageDiv.querySelector('.ai-response');
                    aiResponseSpan.innerHTML += '<br><br><span class="text-danger">请求超时，请稍后再试。</span>';
                    showAlert('请求超时', '无法获取AI回复，请稍后再试', 'warning');
                }
            }, 30000); // 30秒超时
            
            // 调用后端API
            fetch('/ai_chat', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    message: message,
                    api_key: API_KEY
                }),
                signal: abortController.signal
            })
            .then(response => response.json())
            .then(data => {
                // 清除超时
                clearTimeout(timeoutId);
                
                if (data.success) {
                    // 模拟流式生成
                    simulateStreamingResponse(data.response, aiMessageDiv.querySelector('.ai-response'));
                } else {
                    // 显示错误消息
                    showAlert('API调用失败', data.message, 'danger');
                    aiMessageDiv.querySelector('.ai-response').innerHTML = '抱歉，我无法回答您的问题。请稍后再试。';
                    resetChatUI();
                }
            })
            .catch(error => {
                // 清除超时
                clearTimeout(timeoutId);
                
                // 如果不是用户主动取消
                if (error.name !== 'AbortError') {
                    console.error('AI聊天请求失败:', error);
                    showAlert('请求失败', '无法连接到AI服务', 'danger');
                    aiMessageDiv.querySelector('.ai-response').innerHTML = '抱歉，我无法回答您的问题。请检查网络连接或稍后再试。';
                } else {
                    aiMessageDiv.querySelector('.ai-response').innerHTML += '<br><br><span class="text-muted">（生成已停止）</span>';
                }
                
                resetChatUI();
            });
        }
        
        // 模拟流式生成
        function simulateStreamingResponse(fullResponse, responseElement) {
            const words = fullResponse.split(' ');
            let currentIndex = 0;
            
            // 重置响应元素
            responseElement.innerHTML = '';
            
            // 模拟流式生成
            const streamInterval = setInterval(() => {
                if (!isGenerating || currentIndex >= words.length) {
                    clearInterval(streamInterval);
                    resetChatUI();
                    return;
                }
                
                // 添加下一个词
                responseElement.innerHTML += (currentIndex > 0 ? ' ' : '') + words[currentIndex];
                currentIndex++;
                
                // 滚动到底部
                const chatContainer = document.querySelector('.chat-container');
                chatContainer.scrollTop = chatContainer.scrollHeight;
            }, 50); // 每50毫秒添加一个词
        }
        
        // 停止生成
        function stopGeneration() {
            if (isGenerating && abortController) {
                abortController.abort();
                isGenerating = false;
                resetChatUI();
            }
        }
        
        // 重置聊天UI
        function resetChatUI() {
            isGenerating = false;
            document.getElementById('send-message').disabled = false;
            document.getElementById('chat-input').disabled = false;
            document.getElementById('send-message').classList.remove('d-none');
            document.getElementById('stop-generation').classList.add('d-none');
        }
        
        // 添加聊天消息
        function addChatMessage(message, sender) {
            const chatContainer = document.querySelector('.chat-container');
            const messageDiv = document.createElement('div');
            
            messageDiv.className = `chat-message ${sender}-message p-3 my-2 ${sender === 'user' ? 'ms-auto' : 'me-auto'}`;
            messageDiv.style.maxWidth = '80%';
            messageDiv.style.borderRadius = '10px';
            messageDiv.style.backgroundColor = sender === 'user' ? '#e9f2f9' : '#f0f5fa';
            
            // 格式化消息内容（支持Markdown）
            let formattedMessage = message;
            
            // 简单的Markdown支持
            // 加粗
            formattedMessage = formattedMessage.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
            // 斜体
            formattedMessage = formattedMessage.replace(/\*(.*?)\*/g, '<em>$1</em>');
            // 换行
            formattedMessage = formattedMessage.replace(/\n/g, '<br>');
            
            if (sender === 'ai') {
                messageDiv.innerHTML = `<i class="bi bi-robot me-2"></i>${formattedMessage}`;
            } else {
                messageDiv.innerHTML = `${formattedMessage}<i class="bi bi-person ms-2"></i>`;
            }
            
            chatContainer.appendChild(messageDiv);
            chatContainer.scrollTop = chatContainer.scrollHeight;
        }
    }
}); 